'use strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const _ = require('lodash');

const schema = new Schema({
  machine: {type: String, required: true},
  method: {type: String, required: true, lowercase: true},
  userId: {type: String, default: 'public'},
  service: {type: String, required: true},
  requestId: {type: String, required: true, unique: true},
  interface: {type: String, required: true},
  ip:  {type: String, required: true},
  agent: {type: String, required: true},
  url: {type: String, required: true},
  reqBody: {type: Schema.Types.Mixed, required: true, default: {}},
  reqQuery: {type: Schema.Types.Mixed, required: true, default: {}},
  resBody: {type: Schema.Types.Mixed},
  requestTime: {type: Number, required: true},
  responseTime: {type: Number}
});

schema.set('timestamps', true); // createAt, updatedAt -> UTC
schema.set('collection', 'log');
schema.set('minimize', false);

schema.statics.saveReq = function * (body) {
  var {requestId, reqBody, requestTime} = body;
  body.reqQuery = _.isEmpty(body.reqQuery) ? {} : body.reqQuery;
  body.reqBody = _.isEmpty(body.reqBody) ? {} : body.reqBody;
  const result = yield this.create(body);
  return result;
}

schema.statics.saveRes = function * ({requestId, resBody, responseTime}) {
  const query = {requestId};
  const body = _.isEmpty(resBody) ? {} : resBody
  const update = {resBody: body, responseTime}
  const result = yield this.update(query, update);
  return result;
}

const db = require('../config/mongo');
module.exports = db.main.model('Log', schema);
